from flask import Blueprint

from packages.common.base import R
from packages.core.auth.decorators import HasPerm
from packages.common.base_model import db
from modules.sys.services.post_service import PostService
from packages.common.base import IdForm, IdsForm
from modules.sys.validators.post_validator import PostForm, PostPageForm

# 声明一个蓝图
post = Blueprint("post", __name__, url_prefix="/sys/post")

# 声明一个岗位业务服务
post_service = PostService(db=db)


@post.route("/detail", methods=["POST"])
@HasPerm(access="sys:post:detail", name="通过id获取岗位信息")
def post_detail():
    """
    通过id获取岗位信息
    :return:
    """
    form = IdForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # 或者直接拿id值 id=form.id.data
    # u = Post.query.filter_by(id=form.id.data).first()
    # 通过主键查询
    u = post_service.detail(form)
    if u is not None:
        return R.data(u.to_dict())
    else:
        return R.fail("该记录不存在")


@post.route("/page", methods=["POST"])
@HasPerm(access="sys:post:page", name="分页查询岗位列表")
def post_page():
    """
    分页查询岗位列表
    :return:
    """
    form = PostPageForm()
    form.validate_for_api()
    return R.data(post_service.page(form))


@post.route("/save", methods=["POST"])
@HasPerm(access="sys:post:save", name="添加岗位")
def post_save():
    """
    添加岗位
    :return:
    """
    form = PostForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    post_service.save(form)
    return R.success("添加岗位成功")


@post.route("/update", methods=["POST"])
@HasPerm(access="sys:post:update", name="修改岗位")
def post_update():
    """
    修改岗位
    :return:
    """
    form = PostForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    post_service.update(form)
    return R.success("修改岗位成功")


@post.route("/remove", methods=["POST"])
@HasPerm(access="sys:post:remove", name="删除岗位")
def post_remove():
    """
    删除岗位
    :return:
    """
    form = IdsForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    post_service.remove(form)
    return R.success("删除岗位成功")
